// pages/server_end/editinfo/editinfo.js
const app = getApp();
const request = require('../../../utils/request.js');
const url = require('../../../utils/url.js');
const cookie = require('../../../utils/cookie.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    contact_name: "",
    contact_tel: "",
    postcode: "",
    addr:"",
    addr_detail: "",
    sevice_category_id: 0,
    desc: "",
    setlocation:0,
    lat:0,
    lng:0,
    uploadfront: 0,
    uploadback: 0,
    idcard_front_image: "",
    idcard_front_image_url: "/static/icon/icon_upload_id1.png",
    idcard_back_image: "",
    idcard_back_image_url: "/static/icon/icon_upload_id2.png",
    regionValue: '',
    serverType:"",
    serverTypeRange: [],
    servicetaglist:[],
    taglist:[],
    tagIds:[],
    imgs: [],
    picList: [],
    token: "",
    show: 0,
    show1: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    cookie.getCookie('userInfo', function (res) {
      if (res) {
        var etime = Date.parse(new Date()) / 1000;
        
        if (etime < res.expiretime) {
          that.setData({
            login: 1,
            token:res.token
          })
          that.getWorkerInfo();
          that.getServiceTag();
          that.getServiceType();
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  changecontactname(e){
    this.setData({
      contact_name:e.detail.value
    })
  },
  changecontacttel(e){
    this.setData({
      contact_tel:e.detail.value
    })
  },
  changeaddr(e){
    this.setData({
      addr_detail:e.detail.value
    })
  },
  changedesc(e){
    this.setData({
      desc:e.detail.value
    })
  },
  getServiceTag(){
    var that = this;
    let param = {
      scoure: 'wxapp',
      token:that.data.token
    }
    wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
    request.request(url.servicetaglist, param, url.REQUEST_METHOD_GET).then((res) => {
      wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
      if(res.data.code==1){
         that.setData({
            servicetaglist : res.data.data
         })
       }
    })  	
  },
  getServiceType(){
    var that = this;
    let param = {
      scoure: 'wxapp',
      token:that.data.token
    }
    wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
    request.request(url.secondcategorylist, param, url.REQUEST_METHOD_GET).then((res) => {
      wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
      if(res.data.code==1){
         that.setData({
            serverTypeRange : res.data.data
         })
       }
    })  	
  },
  getWorkerInfo:function(){
    var that = this;
    let param = {
      scoure: 'wxapp',
      token:that.data.token
    }
    wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
    request.request(url.workerinfo, param, url.REQUEST_METHOD_GET).then((res) => {
      wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
      if(res.data.code==1){
         that.setData({
          contact_name : res.data.data.contact_name,
          contact_tel: res.data.data.contact_tel,
          addr : res.data.data.addr,
          addr_detail : res.data.data.addr_detail,
          service_tag_ids : res.data.data.service_tag_ids,
          desc : res.data.data.desc,
          setlocation : 1,
          taglist : res.data.data.tag,
          lat : res.data.data.lat,
          lng : res.data.data.lng,	
          picList : res.data.data.extra_image_arr,
          imgs : res.data.data.extra_image_arr_url,
         })
       }
    })  	
  },
  showtag(){
    this.setData({
       show1:true
    })
  },
  closeTime(){
    this.setData({
      show1:false
   })
  },
  choseTag(e){
    var that=  this; 
    var id =e.currentTarget.dataset.id;
    that.data.servicetaglist.forEach((item,index) => { 
       console.log(item.id);
       if(item.id==id){
         if(item.active==1){
           var active = 0;
          }else{
           var active = 1;
        }
        var sItem = 'servicetaglist['+index+'].active';
        this.setData({
             [sItem] : active
        })
      }
    });
    var array = [];
    var arrayIds = [];
    that.data.servicetaglist.forEach((item,index) => { 				
      if(item.active==1){
         array.push(that.data.servicetaglist[index]);
         arrayIds.push(that.data.servicetaglist[index].id);
      }		
    })   
    that.setData({
       taglist :array,
       tagIds:arrayIds
    })
  },
  regionChange(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
       postcode:e.detail.postcode,
       regionValue:e.detail.value.join('')
    })
  },
  choselocation(){
    var that = this;
    wx.chooseLocation({
      success: function(res) {
        console.log("地图点击事件：" + JSON.stringify(res));
        that.setData({
          addr:res.address,
          lat : res.latitude,
          lng: res.longitude,
          setlocation:1 
        });

      }
    })
  },
 // 删除图片
 deleteImg: function (e) {
  var imgs = this.data.imgs;
  var picList = this.data.picList;
  var index = e.currentTarget.dataset.index;
  imgs.splice(index, 1);
  picList.splice(index, 1);
   this.setData({
         imgs: imgs,
         picList:picList
 });
 console.log(picList);
 },
 chooseImg: function (e) {
    var that = this;
    var imgs = this.data.imgs;
    if (imgs.length >= 3) {
      this.setData({
        lenMore: 1
       });
      setTimeout(function () {
        that.setData({
           lenMore: 0
           });
          }, 2500);
         return false;
    }
    var count = 3 -imgs.length;
    if(count< 1){
      return false;
    }

    wx.chooseImage({
      count: count, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          if (res.errMsg == "chooseImage:ok") {
            wx.showLoading({  //显示loding提示框
              title: '正在上传中...',
            })
            let picList = that.data.picList
            var imgs = that.data.imgs;
            res.tempFilePaths.forEach((item, index) => {
              imgs.push(item)
              that.setData({
                imgs: imgs,
               });
              wx.uploadFile({
                url:  url.HttpServerHostAddress+url.uploadpic,
                filePath: item,
                name: 'file',
                formData: {
                  token: that.data.token
                },
                success: function(res) {
                  let ress = JSON.parse(res.data)
                  if (ress.code == 1) {
                      var picList = that.data.picList;
                      picList.push(JSON.parse(res.data).data.url);
                      that.setData({
                        picList:picList,
                     })
                     console.log(picList);
                  }  else{
                           wx.showToast({
                              title: JSON.parse(res.data).msg,
                              icon: 'none',
                              duration: 3000
                         })
                       return;  } 
                },
                fail: res => {
                  console.log(res)
                }
              })
            })
            wx.hideLoading();  //隐藏loading提示框
          }
     }
    }); 
 },
 save(){
  var that = this;
  if (!that.data.contact_name) {
    wx.showToast({
      title: '请输入姓名',
      icon:'none'
    })
    return false;
  }
  if (!that.data.contact_tel) {
    wx.showToast({
      title: '请输入手机号码',
      icon:'none'
    })
    return false;
  }
  let reg = /^1[0-9]{10}$/
  if (!reg.test(that.data.contact_tel)) {
    wx.showToast({
      title: '请输入正确手机号码',
      icon:'none'
    })
    return false;
  }

  if(!that.data.addr){
    wx.showToast({
      title: '请选择服务地址',
      icon:'none'
    })
    return false;				
  }
  if (!that.data.addr_detail) {
    wx.showToast({
      title: '请输入详细地址',
      icon:'none'
    })
    return false;
  }
  if (!that.data.desc) {
    wx.showToast({
      title: '请输入个人描述',
      icon:'none'
    })
    return false;
  }
  var  arrayIds = [];
  that.data.servicetaglist.forEach((item,index) => { 				
    if(item.active==1){
       arrayIds.push(that.data.servicetaglist[index].id);
    }		
  })
  //that.tagIds = arrayIds;
  that.setData({
    tagIds:arrayIds
  })
  if(that.data.tagIds.length==0){
    wx.showToast({
      title: '请选择服务标签',
      icon:'none'
    })
    return false;					
  }
  let param = {
    scoure: 'wxapp',
    token:that.data.token,
    contact_name: that.data.contact_name,
    contact_tel: that.data.contact_tel,
    addr : that.data.addr,
    addr_detail: that.data.addr_detail,
    lat:that.data.lat,
    lng:that.data.lng,
    desc: that.data.desc,
    service_tag_ids:that.data.tagIds,
    extra_image:that.data.picList
  }
  wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
  request.request(url.workeredit, param, url.REQUEST_METHOD_POST).then((res) => {
    wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
    wx.showToast({
      title: res.data.msg,
      icon:"none"
    });
    if(res.data.code==1){
      setTimeout(function() {
        wx.navigateBack({
          delta: 2
        })
      }, 1500)
      return false;
     }
  })  	
 }
})